package com.kanshu.ksgb.fastread.doudou.module.book.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.dl7.recycler.divider.GridDivider;
import com.dl7.recycler.helper.RecyclerViewHelper;
import com.dl7.recycler.listener.OnRecyclerViewItemClickListener;
import com.dl7.recycler.listener.OnRecyclerViewItemLongClickListener;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseFragment;
import com.kanshu.ksgb.fastread.doudou.common.badge.BadgeNumberManager;
import com.kanshu.ksgb.fastread.doudou.common.badge.BadgeNumberManagerXiaoMi;
import com.kanshu.ksgb.fastread.doudou.common.badge.MobileBrand;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdStyleBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.BaseAdListener;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.presenter.AdPresenter;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.MessageBean;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.ReaderInputParams;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.SignInData;
import com.kanshu.ksgb.fastread.doudou.common.business.event.AdRefreshEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.event.BindEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.event.LoginEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.event.RedPointEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.event.ShelfEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.event.TaskEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.interfaces.IDisposeMessage;
import com.kanshu.ksgb.fastread.doudou.common.business.interfaces.IMainHomeInterface;
import com.kanshu.ksgb.fastread.doudou.common.business.interfaces.ISwitchTab;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVUserManager;
import com.kanshu.ksgb.fastread.doudou.common.business.routerservice.ConfigService;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.ReaderJumpConfig;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DiskLruCacheUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.NetUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.StorageUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.SwipeRefreshHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.view.EmptyLayout;
import com.kanshu.ksgb.fastread.doudou.common.view.LoadingDialog;
import com.kanshu.ksgb.fastread.doudou.common.view.TitlebarView;
import com.kanshu.ksgb.fastread.doudou.module.book.adapter.BookShelfAdapter;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.RecentBookInfo;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ShelfTopData;
import com.kanshu.ksgb.fastread.doudou.module.book.presenter.BookPresenter;
import com.kanshu.ksgb.fastread.doudou.module.book.presenter.ShelfPresenter;
import com.kanshu.ksgb.fastread.doudou.module.book.presenter.ShelfView;
import com.kanshu.ksgb.fastread.doudou.module.book.view.AdBookShelfHeaderLayout;
import com.kanshu.ksgb.fastread.doudou.module.bookcity.listener.BookcaseTopListener;
import com.kanshu.ksgb.fastread.doudou.module.download.event.DeleteDownLoadEvent;
import com.kanshu.ksgb.fastread.doudou.module.download.event.DownloadProgressEvent;
import com.kanshu.ksgb.fastread.doudou.module.message.manager.MessageCenter;
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.SettingManager;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * 套壳app使用
 */
@Route(path = ARouterConfig.HOME_PAGE_NEW_SHELF)
public class NewAdBookShelfFragment extends BaseFragment implements ShelfView, OnRecyclerViewItemClickListener, OnRecyclerViewItemLongClickListener,
        EmptyLayout.OnRetryListener, IDisposeMessage, BookcaseTopListener, ISwitchTab {

    public static final int MAX_COLUMN = 3;

    @BindView(R.id.title_place_holder)
    View mTitlePlaceHolder;
    @BindView(R.id.adContainer)
    FrameLayout mAdContainer;
    @BindView(R.id.recyler_view)
    RecyclerView mRecylerView;
    @BindView(R.id.empty_layout)
    EmptyLayout mEmptyLayout;
    @BindView(R.id.swipe_refresh)
    TwinklingRefreshLayout mSwipeRefresh;
    @BindView(R.id.shelf_del_btn)
    Button mShelfDelBtn;
    @BindView(R.id.title_layout)
    TitlebarView mTitle;
    @BindView(R.id.shelf_sign)
    ImageView mSign;

    private AdBookShelfHeaderLayout mHeaderLayout;
    private LinearLayout mMenuLayout;
    private TextView mSelectAll;
    private TextView mCancelAll;
    private LoadingDialog mLoadingDialog;
    private ImageView mTabPoint;

    private Unbinder unbinder;
    private SignInData mSignInBean;
    private ShelfPresenter mShelfPresenter = new ShelfPresenter(lifeCyclerSubject);
    private BookPresenter mBookPresenter = new BookPresenter(lifeCyclerSubject);

    private List<BookInfo> mBookInfos = new ArrayList<>();
    private List<BookInfo> mNoTopBookInfos = new ArrayList<>();
    private BookShelfAdapter mAdapter;
    private boolean isFirst = true;
    private int mCheckCount;
    private boolean isRefreshRecentRead = false;
    private int mUpdateBookCount;
    private boolean mIsUpdateBadge = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mShelfPresenter.attachView(this);
        EventBus.getDefault().register(this);
        MessageCenter.getInstance().register(this);
        ARouter.getInstance().navigation(ConfigService.class).checkRedPoint();
        isFirst = SettingManager.getInstance().isFirstHomeView();
    }

    @Nullable
    @Override
    @SuppressLint("InflateParams")
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shelf_layout, null);
        unbinder = ButterKnife.bind(this, view);
        mAdapter = new BookShelfAdapter(getActivity(), mNoTopBookInfos);
        initView();
        return view;
    }

    private void initView() {
        int statusBarHeight = DisplayUtils.getStatusBarHeight(getActivity());
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mTitlePlaceHolder.getLayoutParams();
        params.height = statusBarHeight;
        mTitlePlaceHolder.setLayoutParams(params);
        mTitle.goneLeftContainer();
        mTitle.getBack().setVisibility(View.GONE);
        mTitle.setTitle("书架");
        mTitle.getLeftContainer().setOnClickListener(null);
        mHeaderLayout = new AdBookShelfHeaderLayout(getActivity());
        mHeaderLayout.setTopListener(this);
        mAdapter.addHeaderView(mHeaderLayout);
        SwipeRefreshHelper.init(mSwipeRefresh, () -> loadShelfInfo(true));
        mRecylerView.addItemDecoration(new GridDivider(0, 0, MAX_COLUMN, true));
        RecyclerViewHelper.initRecyclerViewG(getActivity(), mRecylerView, mAdapter, MAX_COLUMN);
        mMenuLayout = addMenuLayout(mTitle.getRightContainer());
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemLongClickListener(this);
        mEmptyLayout.setRetryListener(this);

        mSelectAll = addEditModeBtn(mTitle.getLeftContainer(), "全选");
        mSelectAll.setOnClickListener(v -> processSelectAll());
        mCancelAll = addEditModeBtn(mTitle.getRightContainer(), "取消");
        mCancelAll.setOnClickListener(v -> processCancelAll());
        DisplayUtils.gone(mSelectAll, mCancelAll);
        mShelfDelBtn.setOnClickListener(v -> processDelBooks());
        mSign.setOnClickListener(v -> {
            AdPresenter.pvuvStatics(R.string.BOOKSHELF_QIANDAO);
            if(!MMKVUserManager.getInstance().isUserLogin()){
                ARouterUtils.toActivity(ARouterConfig.PERSONAL_LOGIN_IN, "phone", "");
                return;
            }
            ARouter.getInstance().build(ARouterConfig.SIGN_IN_PAGE).withParcelable("data", mSignInBean).navigation();
        });
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleShelfEvent(ShelfEvent shelfEvent) {
        if (shelfEvent.code == ShelfEvent.CANCEL_ALL) {
            processCancelAll();
        } else if (shelfEvent.code == ShelfEvent.DEL_FROM_SHELF_SUCCESS) {
            //删除书籍
            if(mLoadingDialog != null && mLoadingDialog.isShowing()) {
                mLoadingDialog.dismiss();
            }
            List<String> book_ids = (List<String>) shelfEvent.obj;
            for (String book_id : book_ids) {
                for (int i = 0; i < mBookInfos.size(); i++) {
                    if (TextUtils.equals(book_id, mBookInfos.get(i).book_id)) {
                        mBookInfos.remove(i);
                    }
                }
            }
            processCancelAll();
            setTopBookcase();
            mAdapter.notifyDataSetChanged();
            mShelfPresenter.saveNewShelfBooks(mBookInfos);
            SettingManager.getInstance().saveShelfInfos(mBookInfos);
            mSwipeRefresh.setEnableRefresh(true);
        } else if (shelfEvent.code == ShelfEvent.ADD_TO_SHELF_SUCCESS) {
            //刷新书架收藏
            BookInfo bookInfo = (BookInfo) shelfEvent.obj;
            for (BookInfo info : mBookInfos) {
                if (bookInfo.book_id.equals(info.book_id)) {
                    return;
                }
            }
            mBookInfos.add(0, bookInfo);
            wrapBookList();
            setTopBookcase();
            mAdapter.notifyDataSetChanged();
            mShelfPresenter.saveNewShelfBooks(mBookInfos);
            SettingManager.getInstance().saveShelfInfos(mBookInfos);
        } else if (shelfEvent.code == ShelfEvent.REFRESH_RECENT || shelfEvent.code == ShelfEvent.DELETE_RECENT_BOOK) {
            // 刷新最近阅读
            isRefreshRecentRead = true;
            mShelfPresenter.getShelfTopInfo();
        } else if (shelfEvent.code == ShelfEvent.ADD_TO_SHELF) {
            // 添加到书架中
            String bookId = (String) shelfEvent.obj;
            mBookPresenter.joinBookShelf(bookId);
        } else if (shelfEvent.code == ShelfEvent.UPDATE_BOOK_STATUS) {
            String bookId = (String) shelfEvent.obj;
            for (int i = 0; i < mBookInfos.size(); i++) {
                if (TextUtils.equals(bookId, mBookInfos.get(i).book_id)) {
                    mBookInfos.get(i).is_updated = false;
                    mAdapter.notifyItemChanged(i + mAdapter.getHeaderViewsCount());
                    DiskLruCacheUtils.put(SettingManager.getShelfBookKey(), mBookInfos, true);
                    mUpdateBookCount--;
                    break;
                }
            }
            updateAppCount(mUpdateBookCount >= 0 ? mUpdateBookCount : 0);
            setTopBookcase();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleTaskEvent(TaskEvent taskEvent) {
        if (taskEvent.type == TaskEvent.SIGN_IN) {
            DisplayUtils.gone(mSign);
            StorageUtils.setPreference(getActivity(), Constants.SP_NAME, "signed_today_" + UserUtils.getUserId(), false);
            // 设置主框架的小红点
            if (getActivity() != null && getActivity() instanceof IMainHomeInterface) {
                ((IMainHomeInterface) getActivity()).setRedPoint();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleBindEvent(BindEvent bindEvent) {
        if (bindEvent.code == BindEvent.SUCCESS) {
            loadShelfInfo(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleLoginEvent(LoginEvent event) {
        processCancelAll();
        loadShelfInfo(true);
        ARouter.getInstance().navigation(ConfigService.class).checkRedPoint();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleDownloadProgressEvent(DownloadProgressEvent event) {
        if(event.isGroupFinish) {
            if(mHeaderLayout != null){
                mHeaderLayout.refreshRecentRead();
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleDeleteDownLoadEvent(DeleteDownLoadEvent event) {
        if(mHeaderLayout != null){
            mHeaderLayout.refreshRecentRead();
        }
        mAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleAdRefreshEvent(AdRefreshEvent event) {
        DisplayUtils.visible(mAdContainer);
        AdUtils.fetchAdUtil(Objects.requireNonNull(getActivity()), mAdContainer, null, ADConfigBean.POSITION_SHELF_TOP_BANNER_SJ_0, AdStyleBean.BANNER_STYLE, 0, new BaseAdListener() {
            @Override
            public void onAdLoadSucceeded(@org.jetbrains.annotations.Nullable View view) {

            }

            @Override
            public void onAdLoadFailed() {
                DisplayUtils.gone(mAdContainer);
            }

            @Override
            public void onAdClicked() {

            }

            @Override
            public void onADClosed() {

            }

            @Override
            public void onBackAd(@NotNull Object ad) {

            }
        });
    }

    /**
     * 加载书籍信息
     * @param load
     */
    private void loadShelfInfo(boolean load) {
        isRefreshRecentRead = false;
        mShelfPresenter.getContentInfo(load);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleRedPointEvent(RedPointEvent event) {
        // 设置主框架的小红点
        if (getActivity() != null && getActivity() instanceof IMainHomeInterface) {
            ((IMainHomeInterface) getActivity()).setRedPoint();
        }
        if (event.obj1 != null) {
            mSignInBean = (SignInData) event.obj1;
        }
        if (event.obj2 != null && mSign != null) {
            boolean signedToday = (boolean) event.obj2;
            mSign.setVisibility(signedToday ? View.GONE : View.VISIBLE);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @SuppressLint("DefaultLocale")
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        loadShelfInfo(true);
        String date = SettingManager.getInstance().getBadgeDate();
        Calendar c = Calendar.getInstance();//
        String str = String.valueOf(c.get(Calendar.YEAR)) +
                String.format("%1$03d", c.get(Calendar.DAY_OF_YEAR));
        if (!TextUtils.equals(date, str)) {
            mIsUpdateBadge = false;
            SettingManager.getInstance().saveBadgeDate(str);
        } else {
            mIsUpdateBadge = true;
        }
        if (!isFirst) {
            AdUtils.fetchAdUtil(Objects.requireNonNull(getActivity()), mAdContainer, null, ADConfigBean.POSITION_SHELF_TOP_BANNER_SJ_0, AdStyleBean.BANNER_STYLE, 0, null);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        MessageCenter.getInstance().unregister(this);
        unbinder.unbind();
        AdUtils.destroyAd(mAdContainer);
    }

    @Override
    public void showShelfBookInfos(List<BookInfo> list, boolean isFromNet) {
        DisplayUtils.visible(mRecylerView);
        SwipeRefreshHelper.swipeRefreshCompleted(mSwipeRefresh, mAdapter);
        mBookInfos.clear();
        mBookInfos.addAll(list);
        wrapBookList();
        setTopBookcase();
        mAdapter.notifyDataSetChanged();
        mUpdateBookCount = 0;
        for (int i = 0; i < mBookInfos.size(); i++) {
            if (mBookInfos.get(i).is_updated) {
                mUpdateBookCount++;
            }
        }
        SettingManager.getInstance().saveShelfInfos(mBookInfos);
        updateAppCount(mUpdateBookCount);
        if (mEmptyLayout != null) {
            mEmptyLayout.hide();
        }
    }

    private void updateAppCount(int count) {
        if (!mIsUpdateBadge) {
            count = 0;
            // 先清零图标数据 并标记为未更新状态
            for (int i = 0; i < mBookInfos.size(); i++) {
                mBookInfos.get(i).is_updated = false;
            }
            DiskLruCacheUtils.put(SettingManager.getShelfBookKey(), mBookInfos, true);
        }
        if (!Build.MANUFACTURER.equalsIgnoreCase(MobileBrand.XIAOMI)) {
            BadgeNumberManager.from(mContext).setBadgeNumber(count);
        } else {
            setXiaomiBadgeNumber(count);
            //小米手机如果在应用内直接调用设置角标的方法，设置角标会不生效,因为在退出应用的时候角标会自动消除
            //这里先退出应用，延迟3秒后再进行角标的设置，模拟在后台收到推送并更新角标的情景
            // moveTaskToBack(true);
        }
    }

    private void setXiaomiBadgeNumber(int count) {
        if (getActivity() == null || count <= 0) {
            return;
        }
        NotificationManager notificationManager = (NotificationManager) mContext.
                getSystemService(Context.NOTIFICATION_SERVICE);
        Intent intent = new Intent();
        intent.setPackage(getActivity().getPackageName());
        intent.setData(Uri.parse(getActivity().getResources().getString(R.string.base_jump_url) + getActivity().getResources().getString(R.string.main)));
        PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0, intent, 0);
        Notification notification = new NotificationCompat.Builder(mContext)
                .setSmallIcon(mContext.getApplicationInfo().icon)
                .setWhen(System.currentTimeMillis())
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText("书籍有更新了")
                .setTicker("ticker")
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .build();
        //相邻的两次角标设置如果数字相同的话，好像下一次会不生效
        BadgeNumberManagerXiaoMi.setBadgeNumber(notification, count);
        assert notificationManager != null;
        if (count > 0) {
            notificationManager.notify(1000, notification);
        }
    }

    @Override
    public void showRecentBookInfos(BaseResult<ShelfTopData> list) {
    }

    @Override
    public void showAddToShelf(BookInfo info) {
    }

    @Override
    public void showNewRecentBookInfos(BaseResult<List<RecentBookInfo>> list) {

    }


    @Override
    public void showContent(ShelfTopData info) {
        if (isRefreshRecentRead) {
            if (info != null) {
                mHeaderLayout.refreshRecentRead(info.zuijin_yuedu);
            }
        } else {
            mHeaderLayout.refresh(info);
        }
    }


    @Override
    public void showError(int errCode, String errDesc) {
    }

    @Override
    public void showLoading(String s) {
        mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_LOADING);
    }

    @Override
    public void dismissLoading() {
        if (mEmptyLayout != null) {
            mEmptyLayout.hide();
        }
    }

    /**
     * 删除书籍
     */
    private void processDelBooks() {
        if (!NetUtils.isNetworkAvailable(getActivity())) {
            ToastUtil.showMessage(getActivity(), getString(R.string.standard_net_tip));
            return;
        }
        if (mCheckCount == 0) {
            ToastUtil.showMessage(getActivity(), "请选择要删除的书本");
            return;
        }
        mLoadingDialog = new LoadingDialog(getActivity(), "加载中");
        mLoadingDialog.show();
        StringBuilder book_ids = new StringBuilder();
        for (int i = mBookInfos.size() - 1; i >= 0; i--) {
            BookInfo bookInfo = mBookInfos.get(i);
            if (BookShelfAdapter.isInvalidBook(bookInfo.book_id)) {
                continue;
            }
            if (bookInfo.is_selected) {
                book_ids.append(bookInfo.book_id).append(",");
            }
        }
        if (book_ids.length() == 0) {
            return;
        }
        // 批量删除
        book_ids = new StringBuilder(book_ids.substring(0, book_ids.length() - 1));
        // 从后台删除
        mBookPresenter.delFromBookShelf(book_ids.toString());
    }

    /**
     * 修饰一下书籍列表
     */
    public void wrapBookList() {
        if (mBookInfos == null) {
            mBookInfos = new ArrayList<>();
        }
        boolean flg = false;
        for (int i = mBookInfos.size() - 1; i >= 0; i--) {
            if (BookInfo.SHELF_ADD_FLAG.equals(mBookInfos.get(i).book_id)) {
                flg = true;
                break;
            }
            if (BookInfo.SHELF_EMPTY_FLAG.equals(mBookInfos.get(i).book_id)) {
                mBookInfos.remove(i);
            }

        }
        if (!flg) {
            mBookInfos.add(mBookInfos.size(), BookInfo.getShelfAdd());
        }
    }

    @Override
    public void onRetry() {
        loadShelfInfo(true);
    }

    private void startReaderActivity(BookInfo bookInfo) {
        int order = TextUtils.isEmpty(bookInfo.c_order) ? 1 : Integer.parseInt(bookInfo.c_order);
        ReaderInputParams params = new ReaderInputParams();
        params.book_id = bookInfo.book_id;
        params.book_title = bookInfo.book_title;
        params.content_id = bookInfo.content_id;
        params.order = order + "";
        ReaderJumpConfig.startReaderActivity(getActivity(), params);
    }

    /**
     * 全选
     */
    private void processSelectAll() {
        int count = 0;
        for (BookInfo bookInfo : mBookInfos) {
            if (!BookShelfAdapter.isInvalidBook(bookInfo.book_id)) {
                bookInfo.is_selected = true;
                count++;
            }
        }
        mCheckCount = count;
        showDelInfo();
        mAdapter.setEditable(true);
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 取消全选
     */
    private void processCancelAll() {
        cancelEditMode();
        for (BookInfo bookInfo : mBookInfos) {
            if (!BookShelfAdapter.isInvalidBook(bookInfo.book_id)) {
                bookInfo.is_selected = false;
            }
        }
        mCheckCount = 0;
        showDelInfo();
        mTitle.setTitle("书架");
        wrapBookList();
        setTopBookcase();
        mAdapter.setEditable(false);
        Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.push_up_out);
        mShelfDelBtn.startAnimation(animation);
        DisplayUtils.gone(mShelfDelBtn);
        if (SwipeRefreshHelper.getRecyclerTopVertical(mRecylerView) >= 0) {
            mSwipeRefresh.setEnableRefresh(true);
        }
    }

    /**
     * 处理删除选中
     */
    private void processCheck(boolean checked) {
        if (checked) {
            mCheckCount++;
        } else {
            mCheckCount--;
        }
        showDelInfo();
    }

    /**
     * 显示删除按钮上的信息
     */
    private void showDelInfo() {
        mShelfDelBtn.setText(getString(R.string.del_format, String.valueOf(mCheckCount)));
    }

    /**
     * 显示编辑模式
     */
    public void showEditMode() {
        DisplayUtils.gone(mMenuLayout);
        DisplayUtils.visible(mSelectAll, mCancelAll);
        if (getActivity() instanceof IMainHomeInterface) {
            ((IMainHomeInterface) getActivity()).setEditable(true);
        }
    }

    /**
     * 取消编辑模式
     */
    public void cancelEditMode() {
        DisplayUtils.visible(mMenuLayout);
        DisplayUtils.gone(mSelectAll, mCancelAll);
        if (getActivity() instanceof IMainHomeInterface) {
            ((IMainHomeInterface) getActivity()).setEditable(false);
        }
    }

    /**
     * 添加编辑按钮
     */
    private TextView addEditModeBtn(FrameLayout container, CharSequence s) {
        TextView tv = new TextView(getActivity());
        tv.setText(s);
        tv.setGravity(Gravity.CENTER);
        tv.setTextColor(Color.parseColor("#333333"));
        tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, DisplayUtils.dip2px(mContext, 15));
        int width = DisplayUtils.dip2px(mContext, 44);
        int height = DisplayUtils.dip2px(mContext, 25);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, height);
        params.gravity = Gravity.CENTER_VERTICAL;
        container.addView(tv, params);
        container.setVisibility(View.VISIBLE);
        return tv;
    }

    /**
     * 添加书架菜单
     */
    @SuppressLint("RtlHardcoded")
    private LinearLayout addMenuLayout(FrameLayout container) {
        LinearLayout menuLayout = new LinearLayout(getActivity());
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT);
        menuLayout.setLayoutParams(lp);
        menuLayout.setOrientation(LinearLayout.HORIZONTAL);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        container.addView(menuLayout, params);
        // 添加搜索
        ImageView searchBtn = new ImageView(getActivity());
        LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        searchBtn.setLayoutParams(lp1);
        searchBtn.setImageResource(R.mipmap.ic_shelf_search_btn);
        searchBtn.setOnClickListener(view -> {
            AdPresenter.Companion.pvuvStatics(R.string.SJSEARCH);
            ARouterUtils.toActivity(ARouterConfig.SEARCH);
        });
        menuLayout.addView(searchBtn);
        // 添加消息
        FrameLayout frameLayout = new FrameLayout(getActivity());
        LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        lp2.leftMargin = DisplayUtils.dip2px(getActivity(), 32);
        lp2.width = DisplayUtils.dip2px(getActivity(), 22);
        menuLayout.addView(frameLayout, lp2);
        ImageView messageBtn = new ImageView(getActivity());
        messageBtn.setImageResource(R.mipmap.ic_shelf_msg_btn);
        messageBtn.setOnClickListener(v -> {
            ARouterUtils.toActivity(ARouterConfig.MESSAGE_CENTER);
            DisplayUtils.gone(mTabPoint);
            AdPresenter.Companion.pvuvStatics(R.string.MESSAGE);
            SettingManager.getInstance().saveTabDot(ARouterConfig.HomePageParams.TAB_SHELF, -1);
        });
        FrameLayout.LayoutParams params1 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        frameLayout.addView(messageBtn, params1);
        // 添加小红点
        mTabPoint = new ImageView(getActivity());
        mTabPoint.setImageResource(R.mipmap.ic_tab_point);
        FrameLayout.LayoutParams params2 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
        params2.gravity = Gravity.TOP | Gravity.RIGHT;
        frameLayout.addView(mTabPoint, params2);
        int tabDot = SettingManager.getInstance().getTabDot(ARouterConfig.HomePageParams.TAB_SHELF);
        mTabPoint.setVisibility(tabDot != -1 ? View.VISIBLE : View.GONE);
        return menuLayout;
    }

    @Override
    public void diposeMessage(MessageBean bean) {
        DisplayUtils.visible(mTabPoint);
        SettingManager.getInstance().saveTabDot(ARouterConfig.HomePageParams.TAB_SHELF, 0);
    }

    @Override
    public void switchTab(int tab) {

    }

    @Override
    public void onItemClick(View view, int position) {
        position = position - mAdapter.getHeaderViewsCount();
        if (position >= mBookInfos.size()) {
            return;
        }
        // 编辑模式
        if (mAdapter.isEditable() && !BookShelfAdapter.isInvalidBook(mBookInfos.get(position).book_id)) {
            BookInfo item = mBookInfos.get(position);
            item.is_selected = !item.is_selected;
            processCheck(item.is_selected);
            mAdapter.notifyDataSetChanged();
        } else {
            position = mBookInfos.size() == 1 ? position : position + 1;
            if (position < mBookInfos.size() && position >= 0) {
                if (BookInfo.SHELF_ADD_FLAG.equals(mBookInfos.get(position).book_id)) {
                    ARouterUtils.toActivity(ARouterConfig.HOME_PAGE, "tab_index", String.valueOf(ARouterConfig.HomePageParams.TAB_BOOK_CITY));
                    return;
                } else if (BookInfo.SHELF_EMPTY_FLAG.equals(mBookInfos.get(position).book_id)) {
                    return;
                }
                startReaderActivity(mBookInfos.get(position));
            }
        }
    }

    @Override
    public boolean onItemLongClick(View view, int position) {
        if (mAdapter.isEditable()) {
            return true;
        }
        position = position - mAdapter.getHeaderViewsCount();
        if (position < mBookInfos.size()) {
            BookInfo item = mBookInfos.get(position);
            if (BookShelfAdapter.isInvalidBook(item.book_id)) {
                return true;
            }
            showEditMode();
            mNoTopBookInfos.clear();
            mNoTopBookInfos.addAll(mBookInfos);
            mAdapter.setEditable(true);
            mTitle.setTitle(" ");
            Animation animation = AnimationUtils.loadAnimation(getActivity(), R.anim.push_up_in);
            mShelfDelBtn.startAnimation(animation);
            DisplayUtils.visible(mShelfDelBtn);
            showDelInfo();
            mSwipeRefresh.setEnableRefresh(false);
            return true;
        }
        return false;
    }

    private void setTopBookcase() {
        mNoTopBookInfos.clear();
        mNoTopBookInfos.addAll(mBookInfos);
        if (mNoTopBookInfos.size() > 0 && !BookInfo.SHELF_ADD_FLAG.equals(mNoTopBookInfos.get(0).book_id)) {
            mHeaderLayout.setTopBookInfo(mNoTopBookInfos.get(0));
            mNoTopBookInfos.remove(0);
        } else {
            mHeaderLayout.setTopBookInfo(null);
        }
    }


    @Override
    public void setOnClickListener(BookInfo bookInfo) {
        startReaderActivity(bookInfo);
    }

    @Override
    public void setOnLongClickListener() {
        onItemLongClick(null, mAdapter.getHeaderViewsCount());
    }

    @Override
    public void onDestroy() {
        AdUtils.destroyAd(mAdContainer);
        super.onDestroy();
    }
}
